/**
 * Created by BanAiqin on 2016/11/10.
 */


//项目访问根目录
var basePath = "";
//公共基础类
var bs = {
    /**
     * 根据dataJson填充表单对象
     * @param {Jquery Form Object} formObject 需要设置属性的表单jquery对象
     * @param {Json} dataJson
     */
    loadFormData: function (formObject, dataJson) {
        for (var index in dataJson) {
            var elm = formObject.find("[name='" + index + "']");
            /**
             * radio 赋值
             */
            if ("radio" == elm.attr("type")) {
                for (var i = 0; i < elm.length; i++) {
                    var radio = elm[i];
                    if (radio.value == dataJson[index]) {
                        radio.checked = true;
                    }
                }
            } else {
                if (elm.hasClass('select')) {
                    elm.setValue(dataJson[index]);
                } else {
                    elm.val(dataJson[index]);
                }
            }
        }
    },
    //功能：将浮点数四舍五入，取小数点后1位
    toDecimal1: function (x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return;
        }
        f = Math.round(x * 10) / 10;
        return f;
    },
    //功能：将以s为单位的时间改为mm:ss格式的时间
    toTimeMin: function (t) {
        t = parseInt(t);
        var m = parseInt(t / 60);
        var s = t % 60;
        return m + ":" + s;
    },
    //存放开始时间 结束时间对象
    allTimeElem: {},
    allTimeElemNew: {},
    resetTimeElems: function () {
        var elems = arguments;
        for (var i = 0, n = elems.length; i < n; i++) {
            if (bs.allTimeElem[elems[i]].min > "1600-01-01") {
                bs.allTimeElem[elems[i]].min = "1600-01-01";
            }
            if (bs.allTimeElem[elems[i]].max < "2099-06-16") {
                bs.allTimeElem[elems[i]].max = "2099-06-16";
            }
        }
        laydate.reset();
    },
    dataTime: function (startElem, endElem, format) {
        if (!format) {
            format = "YYYY-MM-DD hh:mm:ss"
        }
        var istime = true;
        if (format == "YYYY-MM-DD") {
            istime = false;
        }
        //日历
        bs.allTimeElem[startElem] = {
            elem: startElem,
            format: format,
            min: "1600-01-01",
            max: "2099-06-16",
            istime: istime,
            istoday: false,
            choose: function (datas) {
                bs.allTimeElem[endElem].min = datas;
                bs.allTimeElem[endElem].start = datas.split(" ")[0] + " 23:59:59";
            },
            cls: function () {
                bs.allTimeElem[endElem].min = '';
            }
        };
        bs.allTimeElem[endElem] = {
            elem: endElem,
            format: format,
            min: "1600-01-01",
            max: "2099-06-16",
            istime: istime,
            istoday: false,
            start: (new Date()).Format("yyyy-MM-dd ") + '23:59:59',
            choose: function (datas) {
                bs.allTimeElem[startElem].start = datas.split(" ")[0] + " 00:00:00";
                bs.allTimeElem[startElem].max = datas
            },
            cls: function () {
                bs.allTimeElem[startElem].max = '';
            }
        };
        laydate(bs.allTimeElem[startElem]);
        laydate(bs.allTimeElem[endElem]);
    },
    resetTimeNew: function (startElem, endElem) {
        bs.allTimeElemNew[endElem].config.min = {
            year: 1900,
            month: 0 //关键
        };
        bs.allTimeElemNew[startElem].config.max = {
            year: 2099,
            month: 11 //关键
        };
    },
    dataTimeNew: function (startElem, endElem, type) {//laydate 新版本支持 指选择月份
        bs.allTimeElemNew[startElem] = laydate.render({
            elem: startElem
            , type: type
            , done: function (value, dates) {
                if (value != "") {
                    bs.allTimeElemNew[endElem].config.min = {
                        year: dates.year,
                        month: dates.month - 1 //关键
                    };
                } else {
                    bs.allTimeElemNew[endElem].config.min = {
                        year: 1900,
                        month: 0 //关键
                    };
                }
            }
        });
        bs.allTimeElemNew[endElem] = laydate.render({
            elem: endElem
            , type: type
            , done: function (value, dates) {
                if (value != "") {
                    bs.allTimeElemNew[startElem].config.max = {
                        year: dates.year,
                        month: dates.month - 1 //关键
                    };
                } else {
                    bs.allTimeElemNew[startElem].config.max = {
                        year: 2099,
                        month: 11 //关键
                    };
                }
            }
        });
    },
    //获取系统配置
    getSysConfig: function (code) {
        var conf;
        //查询单个配置
        var configUrl = basePath + "rest/common/getSysConfigGetByCode";
        $.ajax({
            url: configUrl, timeout: 10000,
            async: false, type: 'POST',
            data: {
                code: code
            },
            success: function (config) {
                conf = config;
            }
        });
        return conf;
    },
    // 获取下拉框数据接口
    getDownData: function (type) {
        var selectArr = [{"name": "全部", "value": ""}];
        $.ajax({
            type: "post",
            url: basePath + "/rest/statusAtt/statusAttsGetByType",
            dataType: "json",
            data: {
                type: type
            },
            async: false,
            success: function (data) {
                var dataArr = data;
                for (var i = 0; i < dataArr.length; i++) {
                    var obj = {};
                    obj.name = dataArr[i].name;
                    obj.value = dataArr[i].value;
                    selectArr.push(obj);
                }
            }
        });
        return selectArr;
    },
    // 初始化下拉框
    selectDown: function ($obj, arr, value, width) {
        var content = arr;
        var w = '150px';
        if (width != null) {
            w = width
        }
        $obj.html("");
        for (var i = 0; i < content.length; i++) {
            var outName = content[i].name;
            var val = content[i].value;
            var $option = $('<option value="' + val + '" hassubinfo="true">' + outName + '</option>')
            $obj.append($option);
        }
        if ($obj.next(".chosen-container").length > 0) {
            $obj.chosen('destroy');
        }
        $obj.chosen({
            no_results_text: '没有数据!',
            width: w,
            disable_search_threshold: 5,
            placeholder_text_multiple: "全部"
        });

        if (value === undefined) {
            if (content.length > 0) {
                $obj.val(content[0].value)
            }
        } else {
            $obj.val(value);
        }
        if (arr.length > 0) {
            if (arr[0].value == "") {
                if (arr.length == 2) {
                    $obj.val(arr[1].value).prop("disabled", true).trigger("chosen:updated");
                } else {
                    $obj.val("").prop("disabled", false).trigger("chosen:updated");
                }
            } else {
                if (arr.length == 1) {
                    $obj.val(arr[0].value).prop("disabled", true).trigger("chosen:updated");
                } else {
                    $obj.val(arr[0].value).prop("disabled", false).trigger("chosen:updated");
                }
            }
        }
        $obj.trigger("chosen:updated");
    },
    // 初始化下拉框
    selectDownNoDisabled: function ($obj, arr, value, width) {
        var content = arr;
        var w = '150px';
        if (width != null) {
            w = width
        }
        $obj.html("");
        for (var i = 0; i < content.length; i++) {
            var outName = content[i].name;
            var val = content[i].value;
            var disabledCode = content[i].disabled;
            var $option = "";
            if (disabledCode) {
                $option = $('<option value="' + val + '" hassubinfo="true" disabled>' + outName + '</option>')
            } else {
                $option = $('<option value="' + val + '" hassubinfo="true">' + outName + '</option>')
            }
            $obj.append($option);
        }
        if ($obj.next(".chosen-container").length > 0) {
            $obj.chosen('destroy');
        }
        $obj.chosen({
            no_results_text: '没有数据!',
            width: w,
            disable_search_threshold: 5,
            placeholder_text_multiple: "全部"
        })

        if (value === undefined) {
            if (content.length > 0) {
                $obj.val(content[0].value)
            }
        } else {
            $obj.val(value);
        }
        $obj.trigger("chosen:updated");
    },
    // bootstrap 下拉框
    selectBootStrap:function($obj,arr,width,noDisabled){
        $obj.html('');
        var w = '150px';
        if (width != null) {
            w = width
        }
        if(typeof($obj.attr("multiple"))!="undefined"){
            if(arr && arr.length>0&&arr[0].value == ''){
                arr.shift();
            }
        }
        if(arr && arr.length>0){
            $.each(arr, function (index, statusConfig) {
                $obj.append("<option value=\"" + statusConfig.value + "\">" + statusConfig.name + "</option>");
            });
            if($obj.data('selectpicker')){
                $obj.selectpicker('destroy');
            }
            var liveSearch = false
            if(arr && arr.length > 5){
                liveSearch = true
            }
            $obj.selectpicker({
                width:w,
                actionsBox:true,
                deselectAllText:'全消',
                selectAllText:'全选',
                selectedText: '',
                // dropupAuto:true,
                liveSearch:liveSearch
            });
            $obj.selectpicker('refresh');
            $obj.selectpicker('render');
            if(arr.length==2 && !noDisabled){
                if(typeof($obj.attr("multiple"))=="undefined"){
                    $obj.selectpicker('val',arr[1].value).prop('disabled',true);
                }
            }else{
                $obj.prop('disabled',false).selectpicker('refresh');
            }
        } else {
            $obj.append("<option value='' disabled></option>");
            if($obj.data('selectpicker')){
                $obj.selectpicker('destroy');
            }
            $obj.selectpicker({
                width:w
            });
        }
    },
    // 过滤多选的下拉框值
    filterSelectVal:function($obj){
        return  $obj.val() !=null ?  $obj.val().join(","):''
    },
    // 获取省份数据
    getProvince: function (code) {
        var provinceArray = [{name: "全部", value: "", id: "", pinyin: ""}];
        if(code == 'CHINA'){
            var pro = $("#spanId", parent.document).attr("data-procode");
            if(!pro){
                provinceArray.push({'name':'全国','value':'CHINA', id: "", pinyin: ""})
            }
        }
        $.ajax({
            url: basePath + "rest/area/showAllAreas",
            type: "post",
            contentType: "application/json",  //缺失会出现URL编码，无法转成json对象
            async: false,
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var province = {};
                    province.name = data[i]['area'];
                    province.value = data[i]['code'];
                    province.id = data[i]['id'];
                    province.pinyin = data[i]['pinyin'];
                    provinceArray.push(province);
                }
            },
            error: function () {

            }
        });
        return provinceArray;
    },
    // 判断数组中有没有重复数据
    isRepeat: function (arr) {
        var hash = {};
        for (var i in arr) {
            if (hash[arr[i]])
                return true;
            hash[arr[i]] = true;
        }
        return false;
    },
    // 根据id 获取姓名 工号
    getUserAccount:function(ids){
        var arr = [];
        $.ajax({
            type: "get",
            url: basePath + "/rest/users/selectUserListById",
            dataType: "json",
            async : false,
            data: {
                userId: ids
            },
            success: function (data) {
                arr = data
            }
        })
        return arr
    },
    // 获取坐席能看到的坐席班组数据
    getMeSeatGroupData: function () {
        var arr = [{
            "name": "全部",
            "value": ""
        }];
        $.ajax({
            type: "get",
            url: basePath + "/rest/users/selectManagedSeatGroup",
            async: false,
            success: function (data) {
                if (data.length > 0) {
                    var dataArr = data;
                    for (var i = 0; i < dataArr.length; i++) {
                        var obj = {};
                        obj.name = dataArr[i].name;
                        obj.value = dataArr[i].id;
                        arr.push(obj);
                    }
                }
            }
        });
        return arr;
    },
    // 获取坐席班组数据
    getSeatGroupData: function (id) {
        var arr = [{
            "name": "全部",
            "value": ""
        }];
        $.ajax({
            type: "post",
            url: basePath + "/rest/group/selectSeatGroup",
            dataType: "json",
            data: {
                areaId: id
            },
            async: false,
            success: function (data) {
                if (data.length > 0) {
                    var dataArr = data;
                    for (var i = 0; i < dataArr.length; i++) {
                        var obj = {};
                        if (dataArr[i]) {
                            obj.name = dataArr[i].name;
                            obj.value = dataArr[i].id;
                        }
                        arr.push(obj);
                    }
                }
            }
        });
        return arr;
    },
    // 获取坐席能看到的坐席数据
    getMeSeatData: function (type) {
        var nameArr = [];
        $.ajax({
            type: "get",
            url: basePath + "/rest/users/selectManagedSeat",
            async: false,
            success: function (data) {
                if (data.length > 0) {
                    var dataArr = data;
                    for (var i = 0; i < dataArr.length; i++) {
                        if (type == "account") {
                            nameArr.push(dataArr[i].account);
                        } else if (type == "realName") {
                            nameArr.push(dataArr[i].realName);
                        } else {
                            nameArr.push(dataArr[i]);
                        }

                    }
                }
            }
        });
        return nameArr;
    },
    // 获取坐席工号数据
    getSeatData: function (areaId, seatGroupId, type) {
        var nameArr = [];
        $.ajax({
            type: "post",
            url: basePath + "/rest/users/selectAccountByAreaGroupId",
            dataType: "json",
            async: false,
            data: {
                areaId: areaId,
                seatGroupId: seatGroupId
            },
            success: function (data) {
                if (data.length > 0) {
                    var dataArr = data;
                    for (var i = 0; i < dataArr.length; i++) {
                        if (type == "account") {
                            nameArr.push(dataArr[i].account);
                        } else if (type == "userName") {
                            nameArr.push(dataArr[i].userName);
                        } else if (type == "realName") {
                            nameArr.push(dataArr[i].realName);
                        } else {
                            nameArr.push(dataArr[i]);
                        }

                    }
                }
            }
        });
        return nameArr;
    },
    // 获取省份下 所有用户
    getAllUsers: function (type) {
        var nameArr = [];
        $.ajax({
            type: "get",
            url: basePath + "/rest/users/showAllUsers",
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.length > 0) {
                    var dataArr = data;
                    for (var i = 0; i < dataArr.length; i++) {
                        if (type != "") {
                            nameArr.push(dataArr[i][type]);
                        } else {
                            nameArr.push(dataArr[i]);
                        }
                    }
                }
            }
        });
        return nameArr;
    },
    // 获取创建人
    getGreatPerson: function (url, type, param) {
        var nameArr = [];
        var ajaxObj = {
            type: "get",
            url: basePath + url,
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.length > 0) {
                    var dataArr = data;
                    for (var i = 0; i < dataArr.length; i++) {
                        if (type != "") {
                            if (dataArr[i] && dataArr[i]["userName"]) {
                                nameArr.push(dataArr[i][type]);
                            }
                        } else {
                            nameArr.push(dataArr[i]);
                        }
                    }
                }
            }
        };
        if (param) {
            ajaxObj.data = param;
        }
        $.ajax(ajaxObj);
        return nameArr;
    },
    // 例如：根据id获取code
    getXInY: function (arr, x, y, val) {
        //例如：根据省份id获取code
        //根据x获取y
        var str = "";
        if (val != "") {
            str = "-1"
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] && arr[i][y]) {
                    if (arr[i][y] == val) {
                        str = arr[i][x];
                        break;
                    }
                }
            }
        }
        return str;
    },
    // 获取下拉框状态
    getStatus: function (type) {
        var dataArr = [{
            name: "全部",
            value: ""
        }];
        $.ajax({
            type: "post",
            url: basePath + "/rest/statusAtt/statusAttsGetByType",
            dataType: "json",
            async: false,
            data: {
                type: type
            },
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var obj = {};
                    obj.name = data[i].name;
                    obj.value = data[i].value;
                    dataArr.push(obj);
                }
            }
        });
        return dataArr;
    },
    // 获取任务数据
    getHasTaskNameData: function (code) {
        var arr = [{
            name: "全部",
            value: ""
        }];
        $.ajax({
            type: "post",
            url: basePath + "/rest/my-accessment/get-data-list-search",
            dataType: "json",
            async: false,
            data: {
                code: code
            },
            success: function (data) {
                if (data.code == 0) {
                    var dataArr = data.data;
                    for (var i = 0; i < dataArr.length; i++) {
                        var obj = {};
                        obj.name = dataArr[i].workName;
                        obj.value = dataArr[i].workId;
                        arr.push(obj);
                    }
                }
            }
        });
        return arr;
    },
    // 获取已存在任务数据
    getTaskNameData: function (code) {
        var arr = [{
            name: "全部",
            value: ""
        }];
        $.ajax({
            type: "post",
            url: basePath + "/rest/per-task/get-tasks",
            dataType: "json",
            async: false,
            data: {
                "code": code
            },
            success: function (data) {
                if (data.code == 0) {
                    var dataArr = data.data;
                    for (var i = 0; i < dataArr.length; i++) {
                        var obj = {};
                        obj.name = dataArr[i].workname;
                        obj.value = dataArr[i].id;
                        obj.pro = dataArr[i].provincecode;
                        arr.push(obj);
                    }
                }
            }
        });
        return arr;
    },
    // 获取场景
    getSenceData: function (code, id) {
        var arr = [];
        $.ajax({
            type: "POST",
            url: bs.getSysConfig("SJWJ_URL_PRE").value + '/kbdata/getScene',
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify({"city": code, "serviceId": id}),
            crossDomain: true,
            async: false,
            success: function (data) {
                if (data.data) {
                    var result = data.data;
                    arr = [];
                    if (result.length > 0) {
                        for (var i = 0; i < result.length; i++) {
                            var obj = {};
                            var text = result[i].abstract;
                            // obj.value = result[i].kbdataid;
                            obj.value = result[i].abstract;
                            if (text.indexOf(">") > -1) {
                                text = text.substr(text.indexOf(">") + 1);
                            }
                            var subStr = text;
                            var count = (text.split('-')).length - 1;//‘-’共出现几次
                            if (count > 1) {
                                subStr = text.split('-')[0] + "..." + text.split('-')[count];
                            }
                            obj.name = subStr;
                            obj.subTxt = text;
                            arr.push(obj);
                        }
                    }
                }
            }
        });
        return arr;
    },
    // 获取省市
    getProCity: function () {
        $.ajax({
            type: "POST",
            url: basePath + 'rest/common/getProvinceCity',
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify({}),
            async: false,
            success: function (data) {
                var result = data.data;
                $('.city').citypicker({}, result);
            }
        });
    },
    //判断是否为数字
    isNumber: function (value) {
        var patrn = /^(-)?\d+(\.\d+)?$/;
        if (patrn.exec(value) == null || value == "") {
            return false
        } else {
            return true
        }
    },
    // 重置搜索条件
    resetSearch: function (elem, arr) {
        var select = elem.find("select");
        select.each(function () {
            var opLength = $(this).find("option").length;
            if (opLength > 2) {
                var disabled = $(this).attr("disabled");
                if (!disabled) {
                    if (arr) {
                        for (var i = 0; i < arr.length; i++) {
                            if ($(this).attr("id") == arr[i]) {
                                return
                            }
                        }
                        if($(this).hasClass("selectpicker")){
                            $(this).selectpicker('val','').selectpicker('refresh');
                        }else{
                            $(this).val("").trigger("chosen:updated");
                        }
                    } else {
                        if($(this).hasClass("selectpicker")){
                            $(this).selectpicker('val','').selectpicker('refresh');
                        }else{
                            $(this).val("").trigger("chosen:updated");
                        }
                    }
                }
            }
        });
        var input = elem.find("input");
        input.each(function () {
            var disabled = $(this).attr("disabled");
            if (!disabled) {
                if (arr) {
                    for (var i = 0; i < arr.length; i++) {
                        if ($(this).attr("id") == arr[i]) {
                            return
                        }
                    }
                    $(this).val("");
                } else {
                    $(this).val("");
                }

            }
        });
    },
    // 根据状态返回状态名称
    changeState: function (value, arr, type) {
        var str = "";
        value = value + "";
        for (var i = 0; i < arr.length; i++) {
            var stateVal = arr[i].value + "";
            if ((value != "") && (stateVal != "")) {
                if (type) {
                    if (stateVal == value) {
                        str = arr[i].name;
                        break;
                    }
                } else {
                    if (stateVal.indexOf(value) > -1) {
                        str = arr[i].name;
                        break;
                    }
                }
            }
        }
        return str;
    },
    // 根据表格数据返回null 或者 “”都显示“-”
    filterData: function (value) {
        var str = "";
        if (value == null || value == "") {
            str = "-"
        } else {
            str = value
        }
        return str;
    },
    // 对象数组深拷贝
    objArrDeepCopy: function (source) {
        var sourceCopy = source instanceof Array ? [] : {};
        for (var item in source) {
            if (source[item] != null) {
                sourceCopy[item] = typeof source[item] === 'object' ? bs.objArrDeepCopy(source[item]) : source[item];
            } else {
                sourceCopy[item] = ""
            }

        }
        return sourceCopy;
    },
    // 获取页面访问前缀
    getPathName: function () {
        //页面链接：http://localhost:8080/topic/rest/page/login
        var href = window.location.href;
        //访问路径：/topic/rest/page/login
        var path = window.location.pathname;
        //访问路径在页面链接的开始位置
        var index = href.indexOf(path);
        //项目部署主机和端口
        var host = href.substr(0, index);
        //项目名称
        var project = path.substr(0, path.substr(1).indexOf("/") + 2);
        //项目访问根目录=项目部署主机和端口+项目名称
        var result = host + project;
        return result;
    },
    // 数据挖掘页面中 切换城市 跟新业务树
    tabProGetClassify: function (elem,flag) {
        var box = $("body");
        if(elem){
            box = elem
        }
        box.on("click", ".city-select.province a", function () {
            var clickCode = $(this).attr("data-code");
            $("#workAreaId").val(clickCode);
            $("#workNameNew").val('').attr('title','');
            menuWorkNew.init(clickCode,'',flag);//    获取业务数据
            box.find('.tagName').val('')
                .attr('title','')
                .attr('data-relation','')
                .attr('data-id','');
        })
    },
    // 排序
    sortBy: function (field) {
        return function (a, b) {
            return a[field] - b[field];
        }
    },
    // 加载中
    loading: function ($elem) {
        var loadHtml = $('<div class="loaded" style="margin:0 auto">' +
            '<div class="loader">' +
            '<div class="loader-inner line-scale-pulse-out">' +
            '<div></div>' +
            '<div></div>' +
            '<div></div>' +
            '<div></div>' +
            '<div></div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '<div>请稍等，数据正在加载中...</div>');
        $elem.find("tbody tr").remove();
        $elem.find("tbody").append('<tr class="no-records-found"><td style="width:100%" colspan="10"></td></tr>');
        $elem.find("tbody td").html(loadHtml.html());
    },
    autoTableHeight: function(elem,winH) {
        var container = elem.parents('.fixed-table-container');
        var bodyElem = container.find(".fixed-table-body");
        var pageElem = container.find(".fixed-table-pagination");
        var pageHeight=pageElem.height();
        if (pageElem.css('display') == 'none') {
            pageHeight = 0
        }else {
            pageHeight = 59
        }
        container.css({height:(winH-40-pageHeight)});
        container.css({minHeight:450});
        // 是当内容少时，使用搜索功能高度保持不变
        elem.bootstrapTable('resetView',{height:"auto"});
    },
    jumpFormatter:function(value, row, isJump, code){
        var href=basePath + "/rest/page/dataMiningAudioRetrieval";
        var txt = '数据挖掘语音列表';
        if(value!=0 && isJump == 1){ //数量不为0 并且 有跳转权限
            // return '<a href="'+href+'" title="查看语音列表" data-row="'+row+'" data-code="'+code+'" class="J_menuItem" data-index="text'+txt+'"  data-txt="'+txt+'" data-href="/rest/page/dataMiningAudioRetrieval">'+value+'</a>'
            return "<a href='"+href+"' title='查看语音列表' data-row='"+row+"' data-code='"+code+"' class='J_menuItem' data-index='text"+txt+"'  data-txt='"+txt+"' data-href='/rest/page/dataMiningAudioRetrieval'>"+value+"</a>";
        }else{
            return value+""
        }
    }
};//end bs
// 获取业务分类树
var menuWork = {
    init: function (isDisabled, code, jsTreeElem, classifyElem, scenElem) {
        // isDisabled判断是查询页面 下拉框 还是 弹出框里面的下拉框
        if (!jsTreeElem) {
            jsTreeElem = $("#jstree");
        }
        if (!classifyElem) {
            classifyElem = $("#serviceClassify");
        }
        if (!scenElem) {
            scenElem = $("#scene");
        }
        menuWork.render(code, jsTreeElem);
        menuWork.changeMenu(isDisabled, code, jsTreeElem, classifyElem, scenElem);
        menuWork.search(jsTreeElem);
        classifyElem.next().on("click", function () {
            jsTreeElem.jstree("deselect_all", true);
            classifyElem.val("").attr("data-id", "");
            $(this).hide();
            if (isDisabled) {
                bs.selectBootStrap(scenElem, [{"name": "请选择", "value": ""}], "100%");
            } else {
                bs.selectBootStrap(scenElem, [{"name": "请选择", "value": ""}]);
            }
            scenElem.selectpicker("val","");
        });
    },
    data: null,
    render: function (code, jsTreeElem) {
        var jstree = jsTreeElem;
        jstree.jstree("destroy");
        jstree.data('jstree', false).empty();
        jstree.jstree({
            "core": {
                "animation": false,
                "multiple": false,
                "check_callback": true,
                'data': function (obj, callback) {
                    var data = [
                        {children: [], id: "投诉", text: "投诉"},
                        {children: [], id: "营销", text: "营销"},
                        {children: [], id: "咨询查询", text: "咨询查询"},
                        {children: [], id: "报障", text: "报障"}
                    ];
                    menuWork.data = data;
                    if (!code) {
                        code = "";
                    }
                    ;
                    $.ajax({
                        type: "POST",
                        url: bs.getSysConfig("SJWJ_URL_PRE").value + '/kbdata/getClassification',
                        dataType: "json",
                        contentType: 'application/json',
                        data: JSON.stringify({
                            // "province": "河北",
                            // "provinceCode": "HE"
                            "city": code
                        }),
                        // async: false,
                        success: function (data) {
                            var result = data.data;
                            if (result != null) {
                                var arr = [];
                                arr.push(result);
                                callback.call(this, menuWork.loopMenu(arr));
                            }
                        }
                    });
                }
            },
            "types": {
                "default": {
                    "icon": "jstree-folder"
                },
                "html": {
                    "icon": "jstree-file"
                }
            },
            "plugins": ["types", "search", "unique"]
        }).bind('loaded.jstree', function (e, data) {
            jstree.jstree("deselect_all", true);
            $("li[aria-selected='true']").click();

        })
    },
    rootLoopMenu: function (array, obj) {
        if (array.length > 0) {
            var parentid = obj.parentid;
            for (var i = 0; i < array.length; i++) {
                var code = 0;
                var id = array[i]["id"];
                if (parentid == id) {
                    array[i]["children"].push(obj);
                    return array;
                } else {
                    code++;
                }
                if (code == array.length) {
                    for (var j = 0; j < code; j++) {
                        menuWork.rootLoopMenu(array[j]["children"], obj);
                    }
                }
            }
            return array;
        }
    },
    loopMenu: function (array, j) {
        if (array && array.length > 0) {
            if (!j) {
                j = 1
            }
            for (var i = 0; i < array.length; i++) {
                var children = array[i]["children"];
                array[i]["id"] = array[i]["serviceid"];
                array[i]["text"] = array[i]["service"];
                if (children) {
                    if (children.length <= 0) {
                        array[i].type = "html"
                    }

                }
                if (j > 1) {
                    array[i].state = {"opened": false}
                } else {
                    array[i].state = {"opened": true}
                }
                if (children) {
                    menuWork.loopMenu(children, j + 1);
                }
            }
            return array;
        } else {
            return []
        }
    },
    changeMenu: function (isDisabled, code, jsTreeElem, classifyElem, scenElem) {
        jsTreeElem.on("changed.jstree", function (e, data) {
            classifyElem.val(data.node.text).attr("data-id", data.selected[0]);
            classifyElem.next().show();
            var sceneArr = bs.getSenceData(code, data.selected[0]);
            sceneArr.unshift({"name": "请选择", "value": ""});
            if (isDisabled) {
                bs.selectBootStrap(scenElem, sceneArr, "100%");
            } else {
                bs.selectBootStrap(scenElem, sceneArr);
            }
            scenElem.attr("data-msg", JSON.stringify(sceneArr));
            scenElem.unbind("chosen:showing_dropdown").bind("chosen:showing_dropdown", function () {
                scenElem.next().find("li").hover(function () {
                    var index = $(this).attr("data-option-array-index");
                    $(this).attr("title", sceneArr[index]['subTxt'])
                })
            });
        });

    },
    search: function (jsTreeElem) {
        $("#searchMenu").on("click", function () {
            jsTreeElem.jstree(true).search($.trim($(".search_box input").val()));
            menuWork.scrollSearch(jsTreeElem.parent());
        });
        jsTreeElem.parent().prev().find("input").on("keyup", function (e) {
            e.stopPropagation();
            var code = e.charCode || e.keyCode;
            if (code == 13) {
                jsTreeElem.jstree(true).search($.trim($(this).val()));
                menuWork.scrollSearch(jsTreeElem.parent());
            }
        })
    },
    scrollSearch: function (elem) {
        if (elem.find(".jstree-search").length > 0) {
            var odiv = elem.find(".jstree-search").eq(0)[0];
            var top = odiv.offsetTop;
            var height = odiv.offsetHeight;
            var elemTop = elem[0].scrollTop;
            //获取当前屏幕大小
            var size = elem.height();
            //加上元素本身的高度，是元素全部出现事件
            if ((top + height) < (elemTop + size) && (top + height) > elemTop) {

            } else {
                elem.animate({scrollTop: top - 70}, "slow");
            }
        } else {
            toastrCog.error("没有匹配数据！")
        }
    },
};
// 获取业务分类树--新
var menuWorkNew = {
    init: function (code, jsTreeElem, flag) {
        // isDisabled判断是查询页面 下拉框 还是 弹出框里面的下拉框
        if (!jsTreeElem) {
            jsTreeElem = $("#jstree");
        }
        menuWorkNew.render(code, jsTreeElem, flag);
        menuWorkNew.changeMenu(code, jsTreeElem);
        menuWorkNew.search(jsTreeElem);
    },
    data: null,
    render: function (code, jsTreeElem, flag) {
        var jstree = jsTreeElem;
        jstree.jstree("destroy");
        jstree.data('jstree', false).empty();
        jstree.jstree({
            "core": {
                "animation": false,
                "multiple": false,
                "check_callback": true,
                'data': function (obj, callback) {
                    var data = [
                        {children: [], id: "投诉", text: "投诉"},
                        {children: [], id: "营销", text: "营销"},
                        {children: [], id: "咨询查询", text: "咨询查询"},
                        {children: [], id: "报障", text: "报障"}
                    ];
                    menuWorkNew.data = data;
                    if (!code) {
                        code = "";
                    }
                    ;
                    $.ajax({
                        type: "POST",
                        url: bs.getSysConfig("SJWJ_URL_PRE").value + '/kbdata/getClassification',
                        dataType: "json",
                        contentType: 'application/json',
                        data: JSON.stringify({
                            // "province": "河北",
                            // "provinceCode": "HE"
                            "city": code,
                            'flag': flag
                        }),
                        // async: false,
                        success: function (data) {
                            var result = data.data;
                            if (result != null) {
                                var arr = [];
                                arr.push(result);
                                callback.call(this, menuWorkNew.loopMenu(arr));
                            }
                        }
                    });
                }
            },
            "types": {
                "default": {
                    "icon": "jstree-folder"
                },
                "html": {
                    "icon": "jstree-file"
                }
            },
            "plugins": ["types", "search", "unique"]
        }).bind('loaded.jstree', function (e, data) {
            jstree.jstree("deselect_all", true);
            $("li[aria-selected='true']").click();

        })
    },
    rootLoopMenu: function (array, obj) {
        if (array.length > 0) {
            var parentid = obj.parentid;
            for (var i = 0; i < array.length; i++) {
                var code = 0;
                var id = array[i]["id"];
                if (parentid == id) {
                    array[i]["children"].push(obj);
                    return array;
                } else {
                    code++;
                }
                if (code == array.length) {
                    for (var j = 0; j < code; j++) {
                        menuWorkNew.rootLoopMenu(array[j]["children"], obj);
                    }
                }
            }
            return array;
        }
    },
    loopMenu: function (array, j) {
        if (array && array.length > 0) {
            if (!j) {
                j = 1
            }
            for (var i = 0; i < array.length; i++) {
                var children = array[i]["children"];
                array[i]["id"] = array[i]["serviceid"];
                array[i]["text"] = array[i]["service"];
                if (children) {
                    if (children.length <= 0) {
                        array[i].type = "html"
                    }

                }
                if (j > 1) {
                    array[i].state = {"opened": false}
                } else {
                    array[i].state = {"opened": true}
                }
                if (children) {
                    menuWorkNew.loopMenu(children, j + 1);
                }
            }
            return array;
        } else {
            return []
        }
    },
    changeMenu: function (code, jsTreeElem) {
        jsTreeElem.on("changed.jstree", function (e, data) {
            var selectNode = jsTreeElem.jstree("get_node", data.selected);
            $("#workTreeId").val(selectNode.original.serviceid);
            $("#workTableWin").bootstrapTable("refresh");
        });
    },
    search: function (jsTreeElem) {
        $("#searchMenuWork").on("click", function () {
            jsTreeElem.jstree(true).search($.trim($(this).parent(".search_box").find('input').val()));
            menuWorkNew.scrollSearch(jsTreeElem.parent());
        });
        jsTreeElem.parent().prev().find("input").on("keyup", function (e) {
            e.stopPropagation();
            var code = e.charCode || e.keyCode;
            if (code == 13) {
                jsTreeElem.jstree(true).search($.trim($(this).val()));
                menuWorkNew.scrollSearch(jsTreeElem.parent());
            }
        })
    },
    scrollSearch: function (elem) {
        if (elem.find(".jstree-search").length > 0) {
            var odiv = elem.find(".jstree-search").eq(0)[0];
            var top = odiv.offsetTop;
            var height = odiv.offsetHeight;
            var elemTop = elem[0].scrollTop;
            //获取当前屏幕大小
            var size = elem.height();
            //加上元素本身的高度，是元素全部出现事件
            if ((top + height) < (elemTop + size) && (top + height) > elemTop) {

            } else {
                elem.animate({scrollTop: top - 70}, "slow");
            }
        } else {
            toastrCog.error("没有匹配数据！")
        }
    }
};
// 获取业务分类表格--新
var TableInitWorkNew = function () {
    var oTableInit = new Object();
    var url = bs.getSysConfig("SJWJ_URL_PRE").value + '/kbdata/listPathAndScene';
    //初始化Table
    oTableInit.Init = function (code) {
        $('#workTableWin').bootstrapTable("destroy");
        $('#workTableWin').bootstrapTable({
            url: url,         //请求后台的URL（*）
            method: "post", //请求方式（*）
            dataType: "json",
            height: 540,
            contentType: "application/json",
            dataField: "rows", //服务端返回数据键值 就是说记录放的键值是rows，分页时使用总记录数的键值为total
            totalField: "total",
            striped: true, //是否显示行间隔色
            cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: false, //是否显示分页（*）
            sortable: false, //是否启用排序
            sortName: "id", //排序方式
            sortOrder: "asc", //排序方式
            clickToSelect: true,
            queryParams: oTableInit.queryParams, //传递参数（*）
            queryParamsType: "", //  queryParamsType = 'limit' 参数: limit, offset, search, sort, order;
            sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1, //初始化加载第一页，默认第一页
            pageSize: 10, //每页的记录行数（*）
            pageList: [10, 15, 20, 25], //可供选择的每页的行数（*）
            idField: "id",
            uniqueId: "id", //每一行的唯一标识，一般为主键列
            responseHandler: function (res) {
                var selectArr = workNew.workSelectIdArr;
                var classificationArr = [];
                var sceneArr = [];
                if(res.data){
                    if(res.data.classification){
                        classificationArr = res.data.classification;
                    }
                    if(res.data.scene){
                        sceneArr = res.data.scene;
                    }
                }
                var arr = classificationArr.concat(sceneArr);
                var arr1 = [];
                if (arr.length > 0) {
                    for (var i = 0; i < arr.length; i++) {
                        var obj = {};
                        obj.content = arr[i]
                        arr1.push(obj)
                    }
                }
                if (selectArr.length > 0 && arr1.length > 0) {
                    for (var i = 0; i < arr1.length; i++) {
                        for (var j = 0; j < selectArr.length; j++) {
                            if (selectArr[j].content== arr1[i].content) {
                                arr1[i]["state"] = true;
                            }
                        }
                    }
                }

                return {
                    "total": arr1.length,//总页数
                    "rows": arr1   //数据
                };
            },
            columns: [
                {
                    checkbox: true, // 显示一个勾选框
                    align: 'center', // 居中显示
                    formatter: function (value, row, index) {
                        if (row.state == true)
                            return {
                                disabled: false,//设置是否可用
                                checked: true//设置选中
                            };
                        return value;
                    }
                },
                {
                    align: "center",
                    halign: "center",
                    title: '序号',//标题  可不加
                    width: 60,
                    field: 'id',
                    sortable: true,
                    formatter: function (value, row, index) {
                        var getOptions = $("#workTableWin").bootstrapTable('getOptions');
                        var pagenum = getOptions.pageNumber;
                        var pagesize = getOptions.pageSize;
                        var st = (pagenum - 1) * pagesize;
                        return (st + index + 1) + "";
                    }
                },
                {
                    align: "center",
                    halign: "center",
                    field: 'content',
                    title: '业务分类/场景',
                    sortable: true
                }
            ],
            onLoadSuccess: function (data) {  //加载成功时执行
                workNew.renderSelectWork();
                if (!data.total || data.total == 0) {
                    $(".no-records-found").find("td").html('<img src="../../assert/image/nodata.png" th:src="@{/assert/image/nodata.png}" style="width:165px;" alt="">');
                }
            },
            onLoadError: function () {  //加载失败时执行
                $(".no-records-found").find("td").html('<img src="../../assert/image/nodata.png" th:src="@{/assert/image/nodata.png}" style="width:165px;" alt="">');
            },
            onCheck: function (row, tr) {
                workNew.workSelectIdArr.push(row);
                workNew.renderSelectWork();
            },
            onUncheck: function (row, tr) {
                var content = row.content;
                for (var i = 0; i < workNew.workSelectIdArr.length; i++) {
                    if (workNew.workSelectIdArr[i].content == content) {
                        workNew.workSelectIdArr.splice(i, 1)
                    }
                }
                workNew.renderSelectWork();
            },
            onCheckAll: function (row, tr) {
                var selectArr = $("#workTableWin").bootstrapTable("getSelections");
                var oldArr = bs.objArrDeepCopy(workNew.workSelectIdArr);
                for (var j = 0; j < selectArr.length; j++){
                    var strCode = '';
                    if(oldArr.length>0){
                        for (var i = 0; i < oldArr.length; i++) {
                            if (oldArr[i].content == selectArr[j].content) {
                                strCode += '1'
                            }
                        }
                    }
                    if(strCode.indexOf('1')==-1){
                        workNew.workSelectIdArr.push(selectArr[j])
                    }
                }
                workNew.renderSelectWork();
            },
            onUncheckAll: function (rowsAfter, rowsBefore) {
                var selectArr = rowsAfter;
                for (var j = 0; j < selectArr.length; j++){
                    for (var i = 0; i < workNew.workSelectIdArr.length; i++) {
                        if (workNew.workSelectIdArr[i].content == selectArr[j].content) {
                            workNew.workSelectIdArr.splice(i, 1)
                            break
                        }
                    }
                }
                workNew.renderSelectWork();
            },
            onResetView: function (data) {
                $("#workModal .fixed-table-body").css("maxHeight",500+"px");
            },
            formatLoadingMessage: function () {
                return '<div class="loaded">' +
                    '<div class="loader">' +
                    '<div class="loader-inner line-scale-pulse-out">' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div>请稍等，数据正在加载中...</div>';
            }
        });
    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            "city": $.trim($("#workAreaId").val()),
            "serviceId": $.trim($("#workTreeId").val())
        };
        return temp;
    };
    return oTableInit;
};
// 业务分类相关方法
var workNew = {
    worksArr: null,
    workSelectIdArr: [],
    init: function (proCode, jstree) {
        workNew.selectWork(proCode, jstree);
        $("#workModal #workSModel").on("click", "li b", function () {
            var $li=$(this).parents("li");
            var content = $li.text();
            for(var i=0;i<workNew.workSelectIdArr.length;i++){
                var contentOld=workNew.workSelectIdArr[i].content;
                if(contentOld == content){
                    workNew.workSelectIdArr.splice(i,1)
                }
            }
            $li.remove();
            $("#workTableWin").bootstrapTable('refresh');
        });
    },
    selectWork: function (proCode, jstree) {
        $("#workNameNew").on("click", function () {
            if($("#workAreaId").val()){
                workNew.workSelectIdArr = []
                jstree.prev().find('input').val("");
                jstree.jstree("deselect_all", true);
                var arr = $(this).val().split(',');
                arr.forEach(function (value, key, arr) {
                    var obj = {};
                    obj.content = value;
                    if(value){
                        workNew.workSelectIdArr.push(obj);
                    }
                })
                var workTable = new TableInitWorkNew();
                workTable.Init();
                $("#workModal").modal("show");
            }else{
                toastrCog.error('请选择省份')
            }
        });
        $("#saveWork").on("click", function () {
            var selectArr = workNew.workSelectIdArr;
            var length = selectArr.length;
            var arrName = [];
            for (var i = 0; i < length; i++) {
                var content = selectArr[i].content;
                arrName.push(content);
            }
            $("#workNameNew").val(arrName.join(',')).attr('title',arrName.join(','))
            $("#workModal").modal("hide");
        })
    },
    renderSelectWork:function(){
        var ul=$(".tagSModel ul");
        ul.html("");
        for(var i=0;i<workNew.workSelectIdArr.length;i++){
            var content=workNew.workSelectIdArr[i].content;
            if(content==null){
                content=""
            }
            var $li=$('<li>'+content+'<b class="fa fa-close noPer" style="display: none" title="删除分类"></b></li>');
            $li.hover(function () {
                $(this).find("b").show();
            }, function () {
                $(this).find("b").hide();
            });
            ul.append($li);
        }
    }
}
// 用于查看模型详细信息/规则详细信息
var modelRule = {
    ruleUrl:null,
    init: function (elem, type, param) {
        modelRule.appendModel(elem, type);
        var model = $("#lookModelModal");
        var table=model.find("#commonTable");
        model.modal("show");
        if (type == "model") {
            model.find(".modal-title").html("查看模型");
            var oTableCommon = new TableInitCommon();
            oTableCommon.Init(table,basePath+"rest/model/select/modelById/"+param.modelId,param,modelRule.columnsModel(table),modelRule.onExpandRowModel,modelRule.subTableModel);
        } else if (type == "rule") {
            model.find(".modal-title").html("查看规则");
            var oTableCommon = new TableInitCommon();
            oTableCommon.Init(table, modelRule.ruleUrl+"/combinationRule/getcombinationRulebyid",param,modelRule.columnsRule(table),modelRule.onExpandRowRule,modelRule.subTableRule);
        }
    },
    getRuleUrl:function(){
        modelRule.ruleUrl=bs.getSysConfig("GZGL_URL").value;
    },
    appendModel: function (elem, type) {
        var modelHtml = '<div class="modal fade" id="lookModelModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static">' +
            '<div class="modal-dialog" style="width:1000px;">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span>' +
            '<span class="sr-only">Close</span></button>' +
            '<h4 class="modal-title"></h4>' +
            '</div>' +
            '<div class="modal-body"><table id="commonTable"></table>' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        if (elem.find("#lookModelModal").length == 0) {
            elem.append($(modelHtml));
        }
    },
    columnsModel: function(elem){
        return [
            {
                align: "center",
                halign: "center",
                title: '模型ID',
                width: 60,
                field: 'id',
                visible: false
            },
            {
                align: "center",
                halign: "center",
                field: 'provincecode',
                title: '省份',
                formatter: function (value, row, index) {
                    return row.areaname;
                }
            },
            {
                align: "center",
                halign: "center",
                field: 'name',
                title: '质检模型名称'
            },
            {
                align: "center",
                halign: "center",
                field: 'fullscore',
                title: '质检模型分数'
            },
            {
                align: "center",
                halign: "center",
                field: 'typeid',
                title: '质检模型分类',
                visible: false
            },
            {
                align: "center",
                halign: "center",
                field: 'modeltypename',
                title: '质检模型分类'
            }, {
                align: "center",
                halign: "center",
                field: 'poststatus',
                title: '状态',
                width: 60,
                formatter: function (value, row, index) {
                    var str = "";
                    var color = "#000";
                    if (value == "1") {
                        color = "stateGreen";
                        str="已上线"
                    }else{
                        str="未上线"
                    }
                    return "<span class='" + color + "'>" + str + "</span>";
                }
            }, {
                align: "center",
                halign: "center",
                field: 'testtimes',
                title: '测检状态',
                width: 60,
                formatter: function (value, row, index) {
                    var str = "";
                    var color = "#000";
                    if (value == "1") {
                        color = "stateGreen";
                        str="已测检"
                    }else{
                        str="未测检"
                    }
                    return "<span class='" + color + "'>" + str + "</span>";
                }
            }, {
                align: "center",
                halign: "center",
                field: 'username',
                title: '创建人'
            }, {
                align: "center",
                halign: "center",
                field: 'createtime',
                title: '创建时间',
                formatter: function (value, row, index) {
                    return dateFormatUtil(value);
                }
            }, {
                align: "center",
                halign: "center",
                field: 'onsettime',
                title: '上线时间',
                formatter: function (value, row, index) {
                    return dateFormatUtil(value);
                }
            }, {
                align: "center",
                halign: "center",
                field: 'lastupdatetime',
                title: '最后更新时间',
                formatter: function (value, row, index) {
                    return dateFormatUtil(value);
                }

            }, {
                align: "center",
                halign: "center",
                field: 'note',
                title: '备注',
                formatter: function (value, row, index) {
                    if (value == null) {
                        value = ""
                    }
                    return "<div class='noteBoxTable' title='" + value + "'>" + value + "</div>";
                }
            }
        ]
    },
    columnsRule: function(elem){
        return [
            {
                align: "center",
                halign: "center",
                field: 'rulename',
                title: '规则名称'
            },
            {
                align: "center",
                halign: "center",
                field: 'ruleattributes',
                title: '规则属性',
                formatter: function (value, row, index) {
                    var str="";
                    if (value == "1") {
                        str="人工"
                    }else if (value == "0"){
                        str="系统"
                    }
                    return str;
                }
            },
            {
                align: "center",
                halign: "center",
                field: 'ruleclassify',
                title: '规则分类'
            },
            {
                align: "center",
                halign: "center",
                field: 'author',
                title: '创建人',
//                        visible: false
            },

            {
                align: "center",
                halign: "center",
                field: 'status',
                title: '发布状态',
                width: 60,
                formatter: function (value, row, index) {
                    var str = "";
                    var color = "#000";
                    if (value == "1") {
                        color = "stateGreen";
                        str="已上线"
                    }else{
                        str="未上线"
                    }
                    return "<span class='" + color + "'>" + str + "</span>";
                }
            },
            {
                align: "center",
                halign: "center",
                field: 'publish_time',
                title: '上线时间'
            }, {
                align: "center",
                halign: "center",
                field: 'end_time',
                title: '更新时间'

            }, {
                align: "center",
                halign: "center",
                field: 'fatal',
                title: '致命性',
                formatter: function (value, row, index) {
                    var str="";
                    if (value == "1") {
                        str="是"
                    }else{
                        str="否"
                    }
                    if(row.sign_default_score == 1) {
                        return ''
                    }else{
                        return str;
                    }
                }
            }, {
                align: "center",
                halign: "center",
                field: 'default_score',
                title: '建议分值',
                formatter: function (value, row, index) {
                    if (value != null) {
                        if (row.sign_default_score == -1) {
                            value = "-" + value;
                        }
                    }
                    return value;
                }
            }, {
                align: "center",
                halign: "center",
                field: 'notes',
                title: '备注'
            }]
    },
    subTableRule:function(){
        return [
            {
                title: '序号',//标题  可不加
                field: 'number',
                width: 60
            },
            {
                field: 'type',
                title: '类型',
                width: 100
            },
            {
                field: 'content',
//                    width: 300,
                title: '内容',
                formatter: function (value, row, index) {
                    var timesStr = "";
                    var voiceSpeedStr = "";
                    var channel = "";
                    var contentStr = "";
                    var durationStr = "";
                    var hitStr = "";
                    if (row.voiceSpeedStr) {
                        voiceSpeedStr = row.voiceSpeedStr;
                    }
                    if (row.timesStr) {
                        timesStr = row.timesStr;
                    }
                    if (row.channel) {
                        channel = row.channel;
                    }
                    if (row.contentStr) {
                        contentStr = row.contentStr;
                    }
                    if (row.durationStr) {
                        durationStr = row.durationStr;
                    }
                    if (row.hit!=null) {
                        var hit = row.hit;
                        if (hit == "0") {
                            hitStr = "否"
                        } else if (hit == "1") {
                            hitStr = "是"
                        }
                    }

                    var conHtml = "";
                    if (voiceSpeedStr) {
                        conHtml += voiceSpeedStr + "</br>";
                    }
                    if (timesStr) {
                        conHtml += timesStr + "</br>";
                    }
                    if (channel) {
                        conHtml += channel + "</br>";
                    }
                    if (contentStr) {
                        conHtml += contentStr + "</br>";
                    }
                    if (durationStr) {
                        conHtml += durationStr + "</br>";
                    }
                    if (hitStr) {
                        conHtml += "命中：" + hitStr + "</br>";
                    }
                    return conHtml;
                }
            },
            {
                field: 'position',
                title: '位置'
            }
        ]
    },
    subTableModel:function(){
        return [
            {
                title: '序号',//标题  可不加
                field: 'id',
                width: 60,
                formatter: function (value, row, index) {
                    return index + 1
                }
            },
            {
                field: 'ruletypename',
                title: '规则分类名称',
            },
            {
                field: 'rulename',
                width: 150,
                title: '规则名称'
            },
            {
                field: 'userfor',
                title: '规则属性',
                formatter: function (value, row, index) {
                    var str = "";
                    if (value == "0") {
                        str = "系统"
                    } else if (value == "1") {
                        str = "人工"
                    }
                    return str;
                }
            },
            {
                field: 'fateful',
                title: '致命性',
                formatter: function (value, row, index) {
                    var str = "";
                    if (value == "0") {
                        str = "否"
                    } else {
                        str = "是"
                    }
                    if(row.signscore == 1) {
                        return ''
                    }else{
                        return str;
                    }
                }
            }, {
                field: 'scorepertime',
                title: '单次分值',
                formatter: function (value, row, index) {
                    if(row.fateful == 1){
                        return '--'
                    }else{
                        return value
                    }
                }
            }, {
                field: 'maxscore',
                title: '分值上限'
            }
        ]
    },
    onExpandRowRule:function(index, row, $detail,columnsSubRule){
        //这一步就是相当于在当前点击列下新创建一个table
        $.ajax({
            url: modelRule.ruleUrl + "/combinationRule/getcombinationRulebyid",
            type: "post",
            data: {
                "idcombinationRule": row.idcombinationrule
            },
            async: false,
            success: function (result) {
                var code = result.code;
                var data = result.data;
                if (code) {
                    if (data) {
                        var textId = data.text;
                        var volumeId = data.volume;
                        var voiceSpeedId = data.voicespeed;
                        var grabId = data.grab;//强插话
                        var channelsId = data.channels;
                        var muteId = data.mute;
                        var negativeId = data.negative;
                        var arr = [];
                        var ruleobj;
                        if (textId) {
                            var textIdArr = textId.split(",");
                            $.each(textIdArr, function (index, value) {
                                ruleobj = modelRule.getRuleOne("文本", value);
                                if (ruleobj) {
                                    arr.push(ruleobj);
                                }
                            });
                        }
                        if (volumeId) {
                            var volumeIdArr = volumeId.split(",");
                            $.each(volumeIdArr, function (index, value) {
                                ruleobj = modelRule.getRuleOne("音量", value);
                                if (ruleobj) {
                                    arr.push(ruleobj);
                                }
                            });
                        }
                        if (voiceSpeedId) {
                            var voiceSpeedIdArr = voiceSpeedId.split(",");
                            $.each(voiceSpeedIdArr, function (index, value) {
                                ruleobj = modelRule.getRuleOne("语速", value);
                                if (ruleobj) {
                                    arr.push(ruleobj);
                                }
                            });
                        }
                        if (grabId) {
                            var grabIdArr = grabId.split(",");
                            $.each(grabIdArr, function (index, value) {
                                ruleobj = modelRule.getRuleOne("抢插话", value);
                                if (ruleobj) {
                                    arr.push(ruleobj);
                                }
                            });
                        }
                        if (channelsId) {
                            var channelsIdArr = channelsId.split(",");
                            $.each(channelsIdArr, function (index, value) {
                                ruleobj = modelRule.getRuleOne("声道", value);
                                if (ruleobj) {
                                    arr.push(ruleobj);
                                }
                            });

                        }
                        if (muteId) {
                            var muteIdArr = muteId.split(",");
                            $.each(muteIdArr, function (index, value) {
                                ruleobj = modelRule.getRuleOne("静音", value);
                                if (ruleobj) {
                                    arr.push(ruleobj);
                                }
                            });
                        }
                        if (negativeId) {
                            var negativeIdArr = negativeId.split(",");
                            $.each(negativeIdArr, function (index, value) {
                                ruleobj = modelRule.getRuleOne("负面情绪", value);
                                if (ruleobj) {
                                    arr.push(ruleobj);
                                }
                            });
                        }
                        row.modelrulelist = arr.sort(bs.sortBy("number"));
                    }
                    SubTable(index, row, $detail,columnsSubRule);
                }
            }
        });
    },
    onExpandRowModel:function(index, row, $detail,columnsSubRule){
        SubTable(index, row, $detail,columnsSubRule);
    },
    getRuleOne: function (type, id) {
        var url = "";
        var params = {};
        if (type == "文本") {
            url = "/text/showchildlisttextbyid";
            params.idtext = id;
        } else if (type == "静音") {
            url = "/mute/showchildlistmutebyid";
            params.idmute = id;
        } else if (type == "音量") {
            url = "/volume/showchildlistvolumebyid";
            params.idvolume = id;
        } else if (type == "语速") {
            url = "/voiceSpeed/showchildlistvoicespeedbyid";
            params.idvoiceSpeed = id;
        } else if (type == "负面情绪") {
            url = "/negative/showchildlistnegativebyid";
            params.idnegative = id;
        } else if (type == "抢插话") {
            url = "/grab/showchildlistgrabbyid";
            params.idgrab = id;
        } else {
            url = "/channels/showchildlistchannelsbyid";
            params.idchannels = id;
        }
        var obj;
        $.ajax({
            url: modelRule.ruleUrl + url,
            type: "post",
            data: params,
            async: false,
            success: function (result) {
                var code = result.code;
                var data = result.data;
                if (code) {
                    obj = data;
                    obj.id = id;
                } else {
                    toastrCog.error(result.message);
                }
            }
        });
        return obj;
    }
};
var TableInitCommon = function () {
    var oTableInitCommon = new Object();
    //初始化Table
    oTableInitCommon.Init = function (elem,url,param,columns,expandFun,columnsSubRule) {
        elem.bootstrapTable("destroy");
        elem.bootstrapTable({
            url: url,         //请求后台的URL（*）
            method: 'post',                      //请求方式（*）
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,    //排序方式
            queryParams: param,//传递参数（*）
            responseHandler: function (res) {
                var arr=[];
                if(res.data){
                    if(Object.prototype.toString.call(res.data)!= '[object Array]'){
                        arr.push(res.data);
                    }else{
                        arr=res.data;
                    }
                }
                return {
                    "total":  1,//总页数
                    "rows": arr  //数据
                };
            },
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            contentType: "application/x-www-form-urlencoded",
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "no",                     //每一行的唯一标识，一般为主键列
            showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: true,
            cellStyle: {
                css: {"background-color": "#fff"}
            },//是否显示父子表
            columns: columns,
            onLoadSuccess: function (data) {  //加载成功时执行
                if (!data.total||data.total == 0) {
                    var src=basePath+"/assert/image/nodata.png";
                    $(".no-records-found").find("td").html('<img src="'+src+'" th:src="@{/assert/image/nodata.png}" style="width:165px;" alt="">');
                }
            },
            onLoadError: function () {  //加载失败时执行
                var src=basePath+"/assert/image/nodata.png";
                $(".no-records-found").find("td").html('<img src="'+src+'" th:src="@{/assert/image/nodata.png}" style="width:165px;" alt="">');
            },
            formatLoadingMessage: function () {
                return '<div class="loaded">' +
                    '<div class="loader">' +
                    '<div class="loader-inner line-scale-pulse-out">' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div>请稍等，数据正在加载中...</div>';
            },
            onExpandRow: function (index, row, $detail) {
                expandFun(index, row, $detail,columnsSubRule)
            },
        });
    };
    //初始化子表格(无线循环)
    SubTable = function (index, row, $detail,columnsSubRule) {
        var cur_table = $detail.html('<table></table>').find('table');
        $(cur_table).bootstrapTable({
            data: row.modelrulelist,
            clickToSelect: true,
            uniqueId: "id",
            pageSize: 10,
            pageList: [10, 25],
            columns: columnsSubRule(),
            onLoadSuccess: function (data) {  //加载成功时执行
                if (!data.total || data.total == 0) {
                    var src = basePath + "/assert/image/nodata.png";
                    $(".no-records-found").find("td").html('<img src="' + src + '" th:src="@{/assert/image/nodata.png}" style="width:165px;" alt="">');
                }
            },
            onLoadError: function () {  //加载失败时执行
                var src = basePath + "/assert/image/nodata.png";
                $(".no-records-found").find("td").html('<img src="' + src + '" th:src="@{/assert/image/nodata.png}" style="width:165px;" alt="">');
            },
            formatLoadingMessage: function () {
                return '<div class="loaded">' +
                    '<div class="loader">' +
                    '<div class="loader-inner line-scale-pulse-out">' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div>请稍等，数据正在加载中...</div>';
            }
        });
    };
    return oTableInitCommon;
};
//获取省市
var proCity = {
    provinces: {},
    citys: {},
    citysAll:{},
    getData: function (flag,boxElem) {
        $.ajax({
            type: "POST",
            url: basePath + 'rest/common/getProvinceCity',
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify({
                "flag": flag
            }),
            async: true,
            success: function (data) {
                var selectBox = boxElem.find('.selectedProCity');
                var selectedBox = boxElem.find('.selectedProCity');
                selectBox.find('span').remove();
                selectedBox.find('span').remove();
                proCity.provinces = [];
                proCity.citys = {};
                var result = data.data;
                if (result != null) {
                    for (var key in result) {
                        if (key == "provinces") {
                            for (var pFlag in result[key]) {
                                proCity.provinces.push(...result[key][pFlag])
                            }
                        } else {
                            proCity.citys[key] = result[key];
                        }
                    }
                    proCity.provinces.sort(function (a, b) {
                        if (a.code.length == b.code.length) {
                            return a.code.localeCompare(b.code);
                        } else {
                            return a.code.length - b.code.length
                        }
                    });
                    proCity.renderPro(proCity.provinces,boxElem);
                    if(flag != '0'){
                        proCity.renderCity(proCity.citys,boxElem);
                    }
                    var $this = boxElem.find('#proCity');
                    if(flag == '0'){
                        if($this.attr('data-type') == 0){
                            var str = $this.attr('data-str');
                            var proStr = $this.attr('data-pro');
                            str = str ? str : '{}';
                            proStr = proStr ? proStr : '{}';
                            var strObj = JSON.parse(str);
                            var proStrObj = JSON.parse(proStr);
                            var name = '';
                            for(var k in strObj){
                                if(strObj[k]){
                                    if(strObj[k].length == 0){
                                        boxElem.find('#jstreePro li[data-pro="'+k+'"]').find('input').attr('checked',true)
                                        name = boxElem.find('#jstreePro li[data-pro="'+k+'"]').find('i').text();
                                        proCity.appendSelectedSpan(k,k,name,boxElem);
                                    }else{
                                        if(strObj[k] instanceof Array){
                                            for(var i=0;i< strObj[k].length;i++){
                                                if(strObj[k][i]){
                                                    boxElem.find('.selectProCity span[data-pro="'+k+'"][data-code="'+strObj[k][i]+'"]').addClass('on');
                                                    name = proCity.citys[k][strObj[k][i]];
                                                    proCity.appendSelectedSpan(k,strObj[k][i],name,boxElem);
                                                }
                                            }
                                        }else{
                                            boxElem.find('.selectProCity span[data-pro="'+k+'"][data-code="'+strObj[k]+'"]').addClass('on');
                                            name = proCity.citys[k][strObj[k]];
                                            proCity.appendSelectedSpan(k,strObj[k],name,boxElem);
                                        }

                                    }
                                }
                            }
                            for(var k in proStrObj){
                                boxElem.find('#jstreePro li[data-pro="'+k+'"]').find('input').attr('checked',true)
                                name = boxElem.find('#jstreePro li[data-pro="'+k+'"]').find('i').text();
                                proCity.appendSelectedSpan(k,k,name,boxElem);
                            }
                        }

                        boxElem.find('#jstreePro').find('li').eq(0).find('i').click();
                    }
                }
            }
        });
    },
    formatter:function(pro,code){
        var obj = {};
        if(pro!=''){
            if(!code){
                obj[pro] = []
            }else{
                if(!code instanceof Array){
                    obj[pro] = [code]
                }else{
                    obj[pro] = code
                }
            }
        }
        return obj
    },
    formatterName:function(pro,code){
        var arr = [];
        if(pro){
            arr.push(pro);
        }
        if(code){
            arr.push(code);
        }
        return arr.join(',')
    },
    init: function (boxElem) {
        var pro=$("#spanId",parent.document).attr("data-procode");
        if(pro){
            boxElem.find('.pro-tab-title li').hide();
        }
        boxElem.find('#proCity').attr('data-str','{}')
            .attr('data-str-search','{}')
            .attr('data-pro','{}');
        proCity.getData('0',boxElem);
        boxElem.find('#proCity').on('click', function () {
            boxElem.find('#proCityModal').modal('show');
        });
        boxElem.find("#proCityModal").on('shown.bs.modal',function(){
            boxElem.find('.selectedProCity').find('span').remove();
            var $this = boxElem.find('#proCity');
            var type = $this.attr('data-type');
            type = type ? type : '0';
            boxElem.find('.pro-tab-title li[data-code="'+type+'"]').click();
        });
        //切换全国、全国5G、重点5G
        boxElem.find('.pro-tab-title').on('click', 'li', function () {
            $(this).addClass('on').siblings().removeClass('on');
            var flag = $(this).attr('data-code');
            proCity.getData(flag,boxElem);
            if(flag == '0'){
                $('#allDelete').show();
            }else{
                $('#allDelete').hide();
            }
        });
        // 选择省份
        boxElem.find('#jstreePro').on('click', 'input', function () {
            var pro = $(this).parent('li').attr('data-pro');
            var name = $(this).parent('li').text();
            if ($(this).prop('checked')) {
                proCity.appendSelectedSpan(pro, pro, name,boxElem);
            } else {
                proCity.removeSelectedSpan(pro, pro,boxElem);
            }
        });
        // 点击省份查询对应城市
        boxElem.find('#jstreePro').on('click', 'i', function () {
            var obj = {};
            if ($(this).hasClass('on')) {
                $(this).removeClass('on');
            } else {
                $('#jstreePro').find('i').removeClass('on');
                $(this).addClass('on');
            }
            var is = boxElem.find('#jstreePro').find('i.on');
            is.each(function (index, elem) {
                var pro = $(elem).parent('li').attr('data-pro');
                obj[pro] = proCity.citys[pro];
            });
            if (is.length == 0) {
                obj = proCity.citys;
            }
            proCity.renderCity(obj,boxElem);
        });
        // 点击城市
        boxElem.find('.selectProCity').on('click', 'span', function () {
            var selectedBox = boxElem.find('.selectedProCity');
            var pro = $(this).attr('data-pro');
            var city = $(this).attr('data-code');
            var name = $(this).html();
            if ($(this).hasClass('on')) {
                $(this).removeClass('on');
                selectedBox.find('span[data-pro="' + pro + '"][data-code="' + city + '"]').remove();
            } else {
                $(this).addClass('on');
                if (selectedBox.find('span[data-pro="' + pro + '"][data-code="' + city + '"]').length == 0) {
                    selectedBox.append('<span data-pro="' + pro + '" data-code="' + city + '">' + name + '</span>');
                }
            }
        });
        // 保存选择的省份/城市
        boxElem.find('#saveProCity').on('click', function () {
            var pro=$("#spanId",parent.document).attr("data-procode");
            var selectedBox = boxElem.find('.selectedProCity');
            var jsonObj = {};
            var nameStr = '';
            var proObj = {};
            selectedBox.find('span').each(function (index, elem) {
                var pro = $(elem).attr('data-pro');
                var code = $(elem).attr('data-code');
                var name = $(elem).text();
                nameStr += name + ',';
                if (!jsonObj[pro]) {
                    jsonObj[pro] = [];
                    if (code && pro != code) {
                        jsonObj[pro].push(code);
                    }
                } else {
                    jsonObj[pro].push(code);
                }
                if(pro == code){
                    if(!proObj[pro]){
                        proObj[pro] = [];
                    }
                }
            });
            nameStr = nameStr.substr(0,nameStr.length-1);
            if(pro == ''&& nameStr == ''){
                if(boxElem.find('.pro-tab-title li.on').attr('data-code') == '0'){
                    nameStr = '全国全部'
                }
            }
            boxElem.find('#proCity').attr('data-str', JSON.stringify(jsonObj))
                .attr('data-pro', JSON.stringify(proObj))
                .val(nameStr)
                .attr('title', nameStr)
                .attr('data-type', boxElem.find('.pro-tab-title li.on').attr('data-code'));
            //如果既选择了省份 有选择了城市 那就按照省份查
            for(var k in jsonObj){
                if(proObj.hasOwnProperty(k)){
                    jsonObj[k] = []
                }
            }
            boxElem.find('#proCity').attr('data-str-search', JSON.stringify(jsonObj))
            boxElem.find('#proCityModal').modal('hide');
        });
        // 省份/城市模态框 显示事件
        boxElem.find("#proCityModal").on('shown.bs.modal',function(){
            boxElem.find("#proCityModal").attr('data-str','{}')
            boxElem.find("#proCityModal").attr('data-str',boxElem.find('#proCity').attr('data-str'))
        });
        // 省份/城市模态框 隐藏事件
        boxElem.find("#proCityModal").on('hidden.bs.modal',function(){
            boxElem.find('#searchProCity').prev().val('');
            if(boxElem.find('#proCity').attr('data-str')){
                var jsonObj = JSON.parse(boxElem.find('#proCity').attr('data-str'));
                var jsonObjP = JSON.parse(boxElem.find('#proCityModal').attr('data-str'));
                var pro = $("#spanId", parent.document).attr("data-procode");
                if(pro == ''){//如果集团人员进来 并且只选择了一个省份 才切换业务树
                    var keys = Object.keys(jsonObj);
                    var proCode = '';
                    if(keys.length == 1){
                        proCode = keys[0];
                    }else{
                        proCode = 'CHINA';
                    }
                    if(Object.keys(jsonObj).sort().toString() != Object.keys(jsonObjP).sort().toString()){
                        boxElem.find("#workAreaId").val(proCode);
                        boxElem.find("#workNameNew").val('').attr('title','');
                        if($('.tagName').length>0){
                            tag.clearTag();
                        }
                        if($("#workAreaId").length>0){
                            menuWorkNew.init(proCode,'',boxElem.find("#proCityModal").attr('data-flag'));//    获取业务数据
                            if($('.tagName').length>0){
                                tag.init($("#workAreaId"),'Search','0',null,false);
                            }
                        }
                    }
                }
            }
        });
        // 删除已选择的省份/城市
        boxElem.find("#proCityModal").on("click", "b", function () {
            var $span=$(this).parents("span");
            var pro = $span.attr('data-pro');
            var code = $span.attr('data-code');
            if(pro == code){//删除省份
                boxElem.find('#jstreePro li[data-pro="'+pro+'"]').find('input').attr('checked',false);
            }else{//删除城市
                boxElem.find('.selectProCity span[data-pro="'+pro+'"][data-code="'+code+'"]').removeClass('on');
            }
            $span.remove();
        });
        // 全部删除 所选省份/城市
        boxElem.find("#proCityModal").on("click", "#allDelete", function () {
            boxElem.find('.selectedProCity').html("");
            boxElem.find('.selectProCity span').removeClass('on');
            boxElem.find('#jstreePro li').find('input').attr('checked',false);
        });
        // 搜索省份/城市
        var proElem = $('#jstreePro');
        var cityElem = $('.selectProCity');
        boxElem.find('#searchProCity').on('click', function () {
            var inputVal = $(this).prev().val();
            var text;
            proElem.find('li').removeClass('search-on');
            cityElem.find('span').removeClass('search-on');
            proElem.find('li').each(function(index,elem){
                text = $(elem).find('i').text();
                if(inputVal && text.indexOf(inputVal)>-1){
                    $(elem).addClass('search-on');
                }
            });
            cityElem.find('span').each(function(index,elem){
                text = $(elem).text();
                if(inputVal && text.indexOf(inputVal)>-1){
                    $(elem).addClass('search-on');
                }
            });
            proCity.scrollSearch(proElem)
            proCity.scrollSearch(cityElem)
        });
        // 回车搜索省份/城市
        boxElem.find('#searchProCity').prev().on("keyup", function (e) {
            e.stopPropagation();
            boxElem.find('#searchProCity').click();
            var code = e.charCode || e.keyCode;
            if (code == 13) {
                proCity.scrollSearch(proElem)
                proCity.scrollSearch(cityElem)
            }
        })
        //全选省份
        boxElem.find('#selectAllPro').on('click',function(){
            boxElem.find('#jstreePro li').find('input').prop('checked',true);
            var dataPro,name;
            boxElem.find('#jstreePro li').each(function(index,elem){
                dataPro = $(elem).attr('data-pro');
                name = $(elem).find('i').text();
                proCity.appendSelectedSpan(dataPro,dataPro,name,boxElem);
            })
        })
        //反选省份
        boxElem.find('#selectReversePro').on('click',function(){
            var dataPro,name;
            //清除所有省份
            boxElem.find('#jstreePro li').each(function(index,elem){
                dataPro = $(elem).attr('data-pro');
                name = $(elem).find('i').text();
                proCity.removeSelectedSpan(dataPro,dataPro,boxElem);
            });
            boxElem.find('#jstreePro li').each(function(index,elem){
                var input  = $(this).find('input');
                input.prop("checked", !input.prop("checked"));
                if(input.prop("checked")){
                    dataPro = $(elem).attr('data-pro');
                    name = $(elem).find('i').text();
                    proCity.appendSelectedSpan(dataPro,dataPro,name,boxElem);
                }
            })
        })
        //全选城市
        boxElem.find('#selectAllCity').on('click',function(){
            boxElem.find('.selectProCity span').addClass('on');
            var dataPro,dataCode,name;
            boxElem.find('.selectProCity span').each(function(index,elem){
                dataPro = $(elem).attr('data-pro');
                dataCode = $(elem).attr('data-code');
                name = $(elem).text();
                proCity.appendSelectedSpan(dataPro,dataCode,name,boxElem);
            })
        })
        //反选城市
        boxElem.find('#selectReverseCity').on('click',function(){
            var dataPro,dataCode,name;
            //清除所有城市
            boxElem.find('.selectProCity span').each(function(index,elem){
                dataPro = $(elem).attr('data-pro');
                dataCode = $(elem).attr('data-code');
                name = $(elem).text();
                proCity.removeSelectedSpan(dataPro,dataCode,boxElem);
            });
            boxElem.find('.selectProCity span').each(function(index,elem){
                $(this).toggleClass('on');
                if($(this).hasClass("on")){
                    dataPro = $(elem).attr('data-pro');
                    dataCode = $(elem).attr('data-code');
                    name = $(elem).text();
                    proCity.appendSelectedSpan(dataPro,dataCode,name,boxElem);
                }
            })
        })
    },
    scrollSearch: function (elem,val) {
        if (elem.find(".search-on").length > 0) {
            var odiv = elem.find(".search-on").eq(0)[0];
            var top = odiv.offsetTop;
            var height = odiv.offsetHeight;
            var elemTop = elem[0].scrollTop;
            //获取当前屏幕大小
            var size = elem.height();
            //加上元素本身的高度，是元素全部出现事件
            if ((top + height) < (elemTop + size) && (top + height) > elemTop) {

            } else {
                elem.animate({scrollTop: top - 100}, "slow");
            }
        }
    },
    renderCity: function (data,boxElem) {//渲染城市
        var selectBox = boxElem.find('.selectProCity');
        var selectedBox = boxElem.find('.selectedProCity');
        var flag = boxElem.find('.pro-tab-title li.on').attr('data-code');
        selectBox.find('span').remove();
        var result = data;
        var $span;
        for (var k in result) {
            for (var key in result[k]) {
                $span = '<span data-pro="' + k + '" data-code="' + key + '">' + result[k][key] + '<b class="fa fa-close" title="删除"></b></span>';
                selectBox.append($span);
                if(flag == '1' || flag == '2'){
                    if (selectedBox.find('span[data-pro="' + k + '"][data-code="' + key + '"]').length == 0) {
                        selectedBox.append($span);
                    }
                }
                if (selectedBox.find('span[data-pro="' + k + '"][data-code="' + key + '"]').length > 0) {
                    selectBox.find('span[data-pro="' + k + '"][data-code="' + key + '"]').addClass('on');
                }
            }
        }
    },
    renderPro: function (data,boxElem) {//渲染省份
        var ulBox = boxElem.find('#jstreePro');
        ulBox.find('li').remove();
        var $li = '';
        for (var i = 0; i < data.length; i++) {
            $li = '<li data-pro="' + data[i].code + '"><input type="checkbox" id="'+data[i].code+'checkbox"><label for="'+data[i].code+'checkbox"></label ><i>' + data[i].area + '</i></li>';
            ulBox.append($li);
            if(boxElem.find('.pro-tab-title li.on').attr('data-code')!='0'){
                if(JSON.stringify(proCity.citys[data[i].code]) == '{}'){
                    ulBox.find('li[data-pro="'+data[i].code+'"] input').prop('checked',true);
                    proCity.appendSelectedSpan(data[i].code,data[i].code,data[i].area,boxElem);
                }
            }
        }
    },
    appendSelectedSpan: function (provinceCode, code, name,boxElem) {
        var $span;
        var selectedBox = boxElem.find('.selectedProCity');
        $span = '<span data-pro="' + provinceCode + '" data-code="' + code + '">' + name + '<b class="fa fa-close" title="删除"></b></span>';
        if(selectedBox.find('span[data-pro="'+provinceCode+'"][data-code="'+code+'"]').length==0){
            if (provinceCode == code) {
                selectedBox.prepend($span);
            } else {
                selectedBox.append($span);
            }
        }
    },
    removeSelectedSpan: function (provinceCode, code,boxElem) {
        var selectedBox = boxElem.find('.selectedProCity');
        selectedBox.find('span[data-pro="' + provinceCode + '"][data-code="' + code + '"]').remove();
    },
    reset:function(boxElem,proName,proCode,type){
        boxElem.find('#proCity').val(proName)
            .attr('data-type',type)
            .attr('data-str',JSON.stringify(proCity.formatter(proCode)))
            .attr('data-pro','{}')
            .attr('data-str-search',JSON.stringify(proCity.formatter(proCode)))
            .attr('title',proCity.formatterName(proCode));
    }
};
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
$(function () {
    modelRule.getRuleUrl();
    basePath = bs.getPathName();
    // ajax全局事件，判断请求超时
    $(document).ajaxError(function (event, xhr, options, exc) {
        console.log(event);
        console.log(xhr);
        console.log(options);
        console.log(exc);
        if (xhr) {
            if (xhr.status == 408) {
                // 登录超时！请重新登录！
                if (window.top != window.self) {
                    window.top.location.href = 'rest/page/login';
                } else {
                    window.location.href = 'rest/page/login';
                }
            } else if (xhr.status == 400) {
                toastrCog.error("系统异常，当前请求无法被服务器理解！")
            } else if (xhr.status == 403) {
                toastrCog.error("系统拒绝，您没有访问权限！")
            } else if (xhr.status == 404) {
                toastrCog.error("请求的资源不存在！")
            } else if (xhr.status == 500) {
                toastrCog.error("服务器遇到错误，无法完成请求！")
            } else if (xhr.status == 503) {
                toastrCog.error("服务器目前无法使用！")
            } else if (xhr.status == 0) {
                toastrCog.error("请求失败！")
            }
            if (xhr.responseText && xhr.responseText.indexOf("rest/user/logins") > -1) {
                window.top.location.href = 'rest/page/login';
            }
        }
    });
});